﻿using ML.IRepository;
using System;
using ML.Entity;
using System.Collections.Generic;
using Dapper;
using MySql.Data.MySqlClient;
namespace ML.Repository
{
    /// <summary>
    /// 收款仓储实现类
    /// </summary>
    public class ReceivablesRepository : DBFactory, IReceivablesRepository
    {
        public Pager<ReceivablesEntity> List(ReceivablesSearch receivablesSearch)
        {
            //组装调用存储过程参数
            var criteria = new PageCriteria() { TableName = "ML_Receivables" };
            criteria.Conditions += string.Format(" AND MerchantId='{0}' AND DelMark=0", receivablesSearch.MerchantId);
            if (!receivablesSearch.Method_Search.Equals("-1"))
            {
                criteria.Conditions += string.Format(" AND Method='{0}'", receivablesSearch.Method_Search);
            }

            criteria.PageIndex = receivablesSearch.pageindex;
            criteria.Field = @"*";
            criteria.PageSize = receivablesSearch.pagesize;
            criteria.SortName = receivablesSearch.ordername;
            if (receivablesSearch.orderby)
            {
                criteria.Sort = "DESC";
            }
            else
            {
                criteria.Sort = "ASC";
            }

            //调用存储过程进行查询并且返回
            var list = GetPageData<ReceivablesEntity>(criteria);
            return list;
        }

        public IEnumerable<ReceivablesEntity> GetReceivablesByMerchantId(string id)
        {
            const string sql = @"SELECT * FROM ml_receivables WHERE MerchantId=@MerchantId AND DelMark=0 ORDER BY DefaultMark DESC,CreateTime DESC";
            using (_db)
            {
                return _db.Query<ReceivablesEntity>(sql, new { @MerchantId = id });
            }
        }

        public ReceivablesEntity GetById(string id)
        {
            throw new NotImplementedException();
        }

        public bool Add(ReceivablesEntity entity)
        {
            const string update_sql = "UPDATE ml_receivables Set DefaultMark=0 WHERE MerchantId=@MerchantId";
            const string add_sql = @"INSERT INTO ml_receivables(Id,MerchantId,Method,OpeningBank,OpeningName,OpeningAccount,ThirdAccount,DefaultMark,DelMark,CreateTime) 
                VALUES (@Id,@MerchantId,@Method,@OpeningBank,@OpeningName,@OpeningAccount,@ThirdAccount,@DefaultMark,@DelMark,@CreateTime);";

            //构造事务、要么执行成功要么执行失败
            using (var conn = OpenConnection())
            {
                MySqlTransaction trans = conn.BeginTransaction();
                var isUpdateTrue = conn.Execute(update_sql, new { @MerchantId = entity.MerchantId }, trans);
                if (isUpdateTrue >= 0)
                {
                    var isAddTrue = conn.Execute(add_sql, entity, trans);
                    if (isAddTrue < 0)
                    {
                        trans.Rollback();
                        return false;
                    }
                    trans.Commit();
                }
                else
                {
                    trans.Rollback();
                    return false;
                }
                return true;
            }
        }

        public bool Update(ReceivablesEntity entity)
        {
            const string sql = @"UPDATE ml_receivables Set Method=@Method,OpeningBank=@OpeningBank,OpeningName=@OpeningName,
                OpeningAccount=@OpeningAccount,ThirdAccount=@ThirdAccount WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool SetDefaultMarkTrue(string Id, int DefaultMark, string merchanctId)
        {
            const string update_sql = "UPDATE ml_receivables Set DefaultMark=0 WHERE MerchantId=@MerchantId";
            const string updateset_sql = "UPDATE ml_receivables Set DefaultMark=@DefaultMark WHERE @Id=Id ";
            using (var conn = OpenConnection())
            {
                MySqlTransaction trans = conn.BeginTransaction();
                var isUpdateTrue = conn.Execute(update_sql, new { @MerchantId = merchanctId }, trans);
                if (isUpdateTrue >= 0)
                {
                    var isUpdateSetTrue = conn.Execute(updateset_sql, new { @DefaultMark = DefaultMark, @Id = Id }, trans);
                    if (isUpdateSetTrue < 0)
                    {
                        trans.Rollback();
                        return false;
                    }
                    trans.Commit();
                }
                else
                {
                    trans.Rollback();
                    return false;
                }
                return true;
            }
        }

        public bool SetDefaultMarkFalse(string Id, int DefaultMark)
        {
            const string updateset_sql = "UPDATE ml_receivables Set DefaultMark=@DefaultMark WHERE @Id=Id ";
            using (_db)
            {
                if (_db.Execute(updateset_sql, new { @DefaultMark = DefaultMark, @Id = Id }) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Delete(ReceivablesEntity entity)
        {
            throw new NotImplementedException();
        }

        public bool Delete(string id)
        {
            const string sql = @"UPDATE ml_receivables SET DelMark = @DelMark WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, new { @DelMark = (int)DeleteStatus.delete_true, @Id = id }) > 0)
                {
                    return true;
                }
                return false;
            }
        }
    }
}